<?php

class FormLogin extends CFormModel{
    public $email;
    public $password;
    public $rememberMe;
    
    public $verifyCode;
    
    private $_identity;
    
    public function rules(){
        return array(
            array('email, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate', 'skipOnError'=>true),
            array('verifyCode', 'captcha', 'allowEmpty' => !extension_loaded('gd'), 'captchaAction' => 'site/captcha', 'on'=>'antiSpam'),
        );
    }
    
    public function attributeLabels(){
        return array(
            'email'=>UserModule::t('fields', 'Email'),
            'password'=>UserModule::t('fields', 'Пароль'),
            'rememberMe'=>UserModule::t('fields', 'Запомнить меня'),
            'verifyCode'=>UserModule::t('fields', 'Код с картинки')
        );
    }
    
    public function authenticate(){
        
        if($this->_identity===null){
            $this->_identity = new UserIdentity();
            $_ident = $this->_identity->auth(
                'email',
                array('email'=>$this->email, 'password'=>$this->password)
            );
            if(!$_ident)
                $this->addError('error', Yii::t('errors', 'Form wrong login or password'));
        }
        
        return $this->_identity;
    }
    
    public function login(){
        
        $this->authenticate();
        
        if($this->_identity->errorCode===UserIdentity::ERROR_NONE){
            $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
            Yii::app()->user->login($this->_identity,$duration);
            return true;
        }else
            return false;
    }
    
    function isShowAntiSpanCaptcha(){
        return @$_SESSION['user']['login'] > USER_ATTEMPS2AUTHORIZE;
    }
}
